<template>
  <div>
    <el-button type="primary" icon="plus" @click="addOrUpdate(1)"
      >新增</el-button
    >
    <el-button type="danger" icon="delete" @click="onBatchRemoveRole"
      >删除</el-button
    >
    <el-button type="info" icon="download" @click="exportExcel"
      >导出</el-button
    >
  </div>
  <el-table :data="tableData" class="table" stripe border>
    <el-table-column width="40">
      <template #header>
        <el-checkbox />
      </template>

      <template #default="{ row }">
        <el-checkbox v-model="row.checked" />
      </template>
    </el-table-column>
    <el-table-column prop="roleName" label="角色名称" align="center" />
    <el-table-column prop="rolePerm" label="权限字符" align="center" />
    <el-table-column label="是否启用" align="center">
      <template #default="{ row }">
        <el-tag>{{ row.enabled }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" align="center" />
    <el-table-column label="操作" align="center">
      <template #default="{ row }">
        <div class="sys-table-main-actions">
          <el-link
            type="primary"
            :underline="false"
            @click="addOrUpdate(2, row)"
          >
            <el-icon><EditPen /></el-icon>
            修改
          </el-link>
          <el-link
            type="danger"
            :underline="false"
            style="margin: 0 8px"
            @click="onRemoveRole(row)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-link>
          <el-dropdown>
            <el-link type="primary" :underline="false">
              更多
              <el-icon><DArrowRight /></el-icon>
            </el-link>
            <template #dropdown>
              <!-- <el-dropdown-menu>
                  <el-dropdown-item v-if="vIf_auth('system:role:assigned')">
                    <router-link
                      :to="`/system/role-assigned?roleId=${row.id}`"
                      class="action-drop-item"
                    >
                      <el-icon><User /></el-icon>
                      <span>分配用户</span>
                    </router-link>
                  </el-dropdown-item>
                </el-dropdown-menu> -->
            </template>
          </el-dropdown>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <!--分页-->
  <pagination
    :pages="pages"
    @changeSize="handleSizeChange"
    @changeCurrent="handleCurrentChange"
  ></pagination>
  <!-- 新增和修改弹窗组件 -->
  <roleEditorDialog
    v-if="editorDialog.show"
    v-model:show="editorDialog.show"
    :type="editorDialog.type"
    :id="editorDialog.id"
    @change="init"
  ></roleEditorDialog>
</template>
<script setup>
import { ref, reactive, computed, onBeforeMount } from "vue";
import roleEditorDialog from "./roleEditorDialog.vue";
import { rolePage, deleteRole } from "@/utils/api/system.ts";
import utils from "@/utils";
// excel插件
import FileSaver from "file-saver";
import * as XLSX from "xlsx";
//分页组件
import pagination from "@/components/common/pagination.vue";
//分页数据
const pages = reactive({
  current: 1, //当前页
  size: 10, //分页大小
  total: 0, //总条数
});
//每一页显示多少条数据
const handleSizeChange = async (val) => {
  pages.size = val;
  await init();
};
//点击页码
const handleCurrentChange = async (val) => {
  pages.current = val;
  await init();
};

// table数据
const tableData = ref([]);
onBeforeMount(async () => {
  await init(); //初始化数据
});
const init = async () => {
  const res = await rolePage({ current: pages.current, size: pages.size });
  res.data.records.forEach((item) => {
    item.createTime = utils.getTime("yyyy-MM-dd", item.createTime);
  });
  tableData.value = res.data.records;
  // 总数
  pages.total = res.data.total;
};

let selectedRows = computed(() => {
  return tableData.value.filter((item) => item.checked === true);
});

/* 新增、修改弹窗 */
const editorDialog = reactive({
  show: false,
});
const addOrUpdate = (type, row) => {
  if (editorDialog.show) return;
  Object.assign(editorDialog, {
    show: true,
    id: row ? row.id : "",
    type,
  });
};

// 删除角色
const onRemoveRole = async (row) => {
  await deleteRole(row.id);
  init();
};

// 批量删除
const onBatchRemoveRole = () => {
  Promise.all(selectedRows.value.map((item) => deleteRole(item.id))).then(
    () => {
      init();
    }
  );
};
// 导出Excel
const exportExcel = () => {
  let time = new Date();
  let year = time.getFullYear().toString();
  let month = (time.getMonth() + 1).toString();
  let day = time.getDate().toString();
  let fileName = year + month + day + Math.random().toString(36).substring(2);
  /**
   *  utils 是 xlsx 库中提供的一些实用工具方法的集合。
      table_to_book 是 utils 对象中的一个方法，用于将 HTML 表格转换为 Excel 工作簿对象。
   */
  let xlsxParam = { raw: true };//转换成excel时，使用原始的格式
  var excel = XLSX.utils.table_to_book(document.querySelector(".table"),xlsxParam);
  var excelWrite = XLSX.write(excel, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([excelWrite], { type: "application/octet-stream;charset=utf-8" }),
      fileName+".xlsx" //2024525wntybbxjiz9.xlsx
    );
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, excelWrite);
  }
  return excelWrite;
};
</script>
